package day04;


import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import untils.UserBehavior;
import untils.itemViewCountPerWindow;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;

/**
 * 每个5分钟统计过去一小时的指标
 * 指标: 每个商品在每个窗口中的访问次数
 * 统计相同结束时间窗口的所有商品点击次数的前三名
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("D:\\atguigu\\flinkdata\\src\\main\\resources\\UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0],arr[1],arr[2],arr[3],Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                            .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                    @Override
                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                        return element.ts;
                    }
                }))
                //对数据根据商品ID进行分区
                .keyBy(r -> r.itemId)
                //每隔5分钟开一个一小时的窗口
                .window(SlidingEventTimeWindows.of(Time.hours(1),Time.minutes(5)))
                //对每个商品在同一窗口的访问次数进行聚合
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {

                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }

                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1L;
                    }

                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }

                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                }, new ProcessWindowFunction<Long, itemViewCountPerWindow, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Long> elements, Collector<itemViewCountPerWindow> out) throws Exception {
                        out.collect( new itemViewCountPerWindow(
                                s,
                                elements.iterator().next(),
                                context.window().getStart(),
                                context.window().getEnd()
                        ));
                    }
                })
                //将同一时间内不同商品分到相同分区
                .keyBy(r -> r.windowEnd)
                //将相同时间段内不同商品根据访问次数进行排序取前三进行输出
                .process(new TopN(3))
                .print();

        env.execute();
    }

    public static class TopN extends KeyedProcessFunction<Long,itemViewCountPerWindow,String> {

        public int n ;

        public TopN(int n) {
            this.n = n;
        }

        private ListState<itemViewCountPerWindow> listState;

        @Override
        public void open(Configuration parameters) throws Exception {
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<itemViewCountPerWindow>("list", Types.POJO(itemViewCountPerWindow.class))
            );
        }

        @Override
        public void processElement(itemViewCountPerWindow value, Context ctx, Collector<String> out) throws Exception {
            listState.add(value);
            ctx.timerService().registerEventTimeTimer(value.windowEnd + 1L);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            ArrayList<itemViewCountPerWindow> arrayList = new ArrayList<>();
            for (itemViewCountPerWindow e : listState.get()) arrayList.add(e);
            listState.clear();

            arrayList.sort(new Comparator<itemViewCountPerWindow>() {
                @Override
                public int compare(itemViewCountPerWindow o1, itemViewCountPerWindow o2) {
                    return  o1.count.intValue() -o2.count.intValue();
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("===============================\n");
            result.append("窗口结束时间：" + new Timestamp(timestamp - 1L) + "\n");
            for (int i = 0; i < n; i++) {
                itemViewCountPerWindow tmp = arrayList.get(i);
                result.append("第" + (i + 1) + "名的商品ID是：" + tmp.itemId + "，浏览次数是：" + tmp.count + "\n");
            }
            result.append("=======================================\n");
            out.collect(result.toString());
        }
    }
}
